//
// Created by le on 13/12/2022.
//

#ifndef PLANEGAME_BULLET_HPP
#define PLANEGAME_BULLET_HPP
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include <random>
#include <vector>

#ifdef __WIN32
#define Main SDL_main
#endif

#ifndef __WIN32
#define Main main
#endif

#define FRAMERATE 60 // 帧率

// 子弹类
class Bullet
{
public:
    Bullet(SDL_Renderer *renderer) : m_v(500), m_imageSurface(NULL), m_imageTexture(NULL)
    {
        m_log = fopen("../static/Bullet.log", "w");
        if (!m_log)
        {
            exit(-1);
        }

        m_imageSurface = IMG_LoadPNG_RW(SDL_RWFromFile("../static/bullet.png", "rb"));
        if (!m_imageSurface)
        {
            fprintf(m_log, "Cannot open bullet.png! Error: %s\n", IMG_GetError());
            exit(-5);
        }

        // 获取图片的宽和高
        m_w = m_imageSurface->w;
        m_h = m_imageSurface->h;

        m_imageTexture = SDL_CreateTextureFromSurface(renderer, m_imageSurface);
        SDL_FreeSurface(m_imageSurface);
        m_imageSurface = NULL;

        if (!m_imageTexture)
        {
            fprintf(m_log, "Cannot create texture!\n");
            exit(-3);
        }
    }

    ~Bullet()
    {
        if (m_log)
        {
            fclose(m_log);
        }

        if (m_imageTexture)
        {
            SDL_DestroyTexture(m_imageTexture);
        }
    }

    // 开始计时
    void start()
    {
        m_start = SDL_GetTicks();
    }

    // 渲染
    void render(SDL_Renderer *renderer, int x, int y, Player *player, int score)
    {
        uint32_t stop = SDL_GetTicks();

        // 每隔一段时间创建新子弹
        if (stop - m_start >= m_v)
        {
            // 创建新子弹
            SDL_Rect srcrect = {x + (player->m_w / 2), y, m_w, m_h};

            m_position.push_back(srcrect);

            if (score >= 100)
            {
                SDL_Rect srcrect1 = {x, y, m_w, m_h};

                m_position.push_back(srcrect1);

                SDL_Rect srcrect2 = {x + player->m_w, y, m_w, m_h};

                m_position.push_back(srcrect2);
            }

            m_start = stop; // 重置计时器
        }

        // 子弹移动
        if (!m_position.empty())
        {
            int i = 0;
            for (i = 0; i < m_position.size(); ++i)
            {
                m_position[i].y -= 2;                                           // 更新位置
                SDL_RenderCopy(renderer, m_imageTexture, NULL, &m_position[i]); // 渲染
            }
        }
    }

    std::vector<SDL_Rect> m_position; // 储存位置信息
    int m_v;                          // 子弹射速

private:
    SDL_Surface *m_imageSurface;
    SDL_Texture *m_imageTexture;
    FILE *m_log; // 日志

    uint32_t m_start;

    int m_w; // 图片的宽
    int m_h; // 图片的高
};

#endif // PLANEGAME_BULLET_HPP
